Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

209
Visualizações
JavaScript | appendChild to all classes

I have problem with append Child to whole classes in my document which the name of class is "onbackorder". Here is my code:

<script>
    var first = document.createElement("p");
    var text = document.createTextNode("On backorder");
    first.appendChild(text);

    var isRequestQuote = document.getElementsByClassName('onbackorder');
    if (isRequestQuote.length > 0) {
        document.querySelector(".onbackorder").appendChild(first);
    }
</script>

For this moment function put selector randomly. How can I get same selector in whole document where class is "onbackorder".

Thank you

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There are 2 points:

  1. document.querySelector(".onbackorder") is just return first item. So you need to use document.querySelectorAll('.onbackorder').

The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

  1. var first = document.createElement("p"); you have to create multiple reference variable to append to each onbackorder item. Because you cannot create only one and append to multiple items.

So I modified your code and make it works. You can check it at below:

var first = document.createElement("p");
var text = document.createTextNode("On backorder");
first.appendChild(text);

const allBackOrders = document.querySelectorAll('.onbackorder');
allBackOrders.forEach((item) => {
  var newItem = first.cloneNode(true);
  item.appendChild(newItem);
});
<div class="onbackorder"></div>
<div class="onbackorder"></div>
<div class="onbackorder"></div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda